import type { OrderItem } from '@/types/api/order'
import type { payKeyItem } from '@/types/pay'
import { orderApi } from '@/request/api'
import { useAppConfig, useGlobalCache } from '@/stores'
import { useConsole, useHideLoading, useLoading, useModal, useNav, useToast } from '@/utils'
import { useAliPay, useKuaishouPay } from '@/utils/pay'
import { to } from 'await-to-js'
import { isNil } from 'lodash-es'

interface BaseOptions {
  oid: OrderItem['id']
}

/** 去支付 */
export async function handleQuZhiFu({ oid }: BaseOptions, paymentChannel?: payKeyItem) {
  useConsole?.log('handleQuZhiFu')

  // #ifdef H5
  // TODO pages/order/orderDetail/orderDetail.vue:548
  // #endif

  // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO || MP-KUAISHOU
  // 先冻结订单
  useLoading(true)
  const payType = UNI_PLATFORM === 'mp-kuaishou' ? paymentChannel?.provider : ''
  const [err, res] = await to(orderApi.freezeApi(oid, {}, payType))
  useHideLoading()
  if (err) {
    return
  }

  // 再支付
  // #ifdef MP-ALIPAY
  await to(useAliPay({ orderStr: res }))
  // #endif
  // #endif

  // 快手支付
  // #ifdef MP-KUAISHOU
  await to(useKuaishouPay({ order_no: res.order_no, order_info_token: res.order_info_token }, paymentChannel))
  // #endif

  uni.$emit('refreshOrderItem', oid)
}

/** 人脸审核 */
export function handleRenLianShenHe({ oid }: BaseOptions) {
  useConsole?.log('handleRenLianShenHe')

  useGlobalCache().currentOrderId = oid

  useNav('/order/face-verify', { oid })
}

/** 签署合同 - 蚂蚁？ */
export async function handleQianShuHeTong({ oid, contractSignflow }: BaseOptions & Pick<OrderItem, 'contractSignflow'>) {
  useConsole?.log('handleQianShuHeTong', contractSignflow)

  useGlobalCache().currentOrderId = oid

  if (!isNil(contractSignflow?.antOrderId)) {
    // const query = {
    //   env: 'prod',
    //   flowId: contractSignflow.flowId,
    //   signerId: contractSignflow.accountId,
    //   skipResult: true,
    //   skipGuide: true,
    // }
    // useConsole?.log('handleQianShuHeTong', query, jsonToQueryString(query))
    // uni.navigateTo({
    //   url: `plugin://esign/esign?${jsonToQueryString(query)}`,
    // })

    // uni.navigateTo({
    //   url: `plugin://esign/esign?env=prod&flowId=${contractSignflow.flowId}&signerId=${contractSignflow.accountId}&skipResult=true&skipGuide=true`,
    // })

    // 创建一个对象来存储参数
    const obj: Record<string, any> = {}
    const paramsArray = contractSignflow.shortUrl.split('?')[1].split('&')
    paramsArray.forEach((param) => {
      const [key, value] = param.split('=')
      if (key) {
        obj[decodeURIComponent(key)] = value ? decodeURIComponent(value) : ''
      }
    })
    useConsole?.log(obj)
    const config = {
      appId: obj.appId,
      path: `${obj.page}?${obj.query}`,
    }
    useConsole?.log(config)
    uni.navigateToMiniProgram(config)
  }
  else {
    useLoading(true)
    const [err, res] = await to(orderApi.sign(oid))
    useHideLoading()
    if (err) {
      return
    }
    uni.navigateToMiniProgram(res)
  }
}

/** 签署合同 - 君子签 */
export async function handleQianShuHeTong_JunZiQian({ oid }: BaseOptions) {
  useConsole?.log('handleQianShuHeTong_JunZiQian')

  useGlobalCache().currentOrderId = oid

  useLoading(true)
  const [err, res] = await to(
    orderApi.jzqGetSignLink({ oid, useCustomDomain: 1 }),
  )
  useHideLoading()
  if (err) {
    return
  }
  // useNav('/webview', { src: encodeURIComponent(res[0].link) })
  useNav('/webview', {
    //   君子签本来地址                      君子签签完跳回小程序的“结果页”                                                       订单详情里的账单页，带 msg 用于一进去的提示
    src: encodeURIComponent(`${res[0].link}&backUrl=${encodeURIComponent(`${import.meta.env.VITE_H5_URL}?type=${UNI_PLATFORM}&path=${encodeURIComponent(`order/bill/list?oid=${oid}&msg=${encodeURIComponent('签约完成，请完成首期支付')}`)}`)}`),
  })
}

/** 签承诺书 */
export async function handleQianChengNuoShu({ oid }: BaseOptions, path: string = 'order/index') {
  useConsole?.log('handleQianChengNuoShu')

  useGlobalCache().currentOrderId = oid

  useLoading(true)
  const [err, res] = await to(orderApi.jzqGetSignLinkPromise({ oid, useCustomDomain: 1 }))
  useHideLoading()
  if (err) {
    return
  }
  useNav('/webview', {
    src: encodeURIComponent(`${res[0].link}&backUrl=${encodeURIComponent(`${import.meta.env.VITE_H5_URL}?type=${UNI_PLATFORM}&path=${encodeURIComponent(path)}`)}`),
  })
}

/** 签收单 */
export async function handleQianShouDan({ oid }: BaseOptions, path: string = 'order/index') {
  useConsole?.log('handleQianShouDan')

  useGlobalCache().currentOrderId = oid

  useLoading(true)
  const [err, res] = await to(orderApi.jzqGetSignLinkPhone({ oid, useCustomDomain: 1 }))
  useHideLoading()
  if (err) {
    return
  }
  useNav('/webview', {
    src: encodeURIComponent(`${res[0].link}&backUrl=${encodeURIComponent(`${import.meta.env.VITE_H5_URL}?type=${UNI_PLATFORM}&path=${encodeURIComponent(path)}`)}`),
  })
}

/** 签署代扣 */
export async function handleQianShuDaiKou({ oid }: BaseOptions) {
  useConsole?.log('handleQianShuDaiKou')

  useGlobalCache().currentOrderId = oid

  // #ifdef H5

  // #endif

  // #ifdef MP-ALIPAY
  useLoading(true)
  const [err, res] = await to(orderApi.queryAntSign(oid))
  useHideLoading()
  if (err) {
    return
  }
  if (!isNil(res)) {
    const query = {
      signStr: res.signStr,
      tenantId: res.tenantId,
      merchantId: res.merchantId,
      orderId: res.orderId,
      redirectUrl: res.redirectUrl,
    }
    useConsole?.log('handleQianShuDaiKou', query)
    // uni.navigateToMiniProgram({
    //   appId: '2021001152620480',
    //   path: `pages/tripartite/index?${jsonToQueryString(query)}`,
    // })
    my.navigateToMiniProgram({
      appId: '2021001152620480',
      path: 'pages/tripartite/index',
      query,
    })
  }
  // #endif
}

/** 查看账单 */
export function handleChaKanZhangDan({ oid }: BaseOptions) {
  useConsole?.log('handleChaKanZhangDan')

  useGlobalCache().currentOrderId = oid

  useNav('/order/bill/list', { oid })
}

/** 售后详情 */
export function handleShouHouXiangQing(/* { oid }: BaseOptions */) {
  // TODO 原项目没有页面
}

/** 确认收货 */
export async function handleQueRenShouHuo({ oid }: BaseOptions) {
  const res = await useModal({
    title: '再次确认',
    content: '确认收货',
    confirmText: '确认',
  })
  if (res.cancel) {
    return
  }

  useLoading(true)
  const [err] = await to(orderApi.receiving(oid))
  useHideLoading()
  if (err) {
    return
  }

  useToast('收货成功', {
    icon: 'success',
  })
  // uni.startPullDownRefresh()
  uni.$emit('refreshOrderItem', oid)
}

/** 自提 */
export function handleZiTi({ shopInfo }: { shopInfo: OrderItem['shopsVo'] }) {
  // 原项目没有页面
  // #ifdef H5 || MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
  uni.openLocation({
    latitude: Number.parseInt(shopInfo.latitude),
    longitude: Number.parseInt(shopInfo.longitude),
    name: shopInfo.name,
    address: shopInfo.address,
    success: () => { },
  })
  // #endif
}

/** 确认自提 */
export async function handleQueRenZiTi(/* { oid }: BaseOptions */) {
  const { cancel } = await useModal({
    title: '温馨提示',
    content: '请您上传自提的商品图片,身份证正面照片',
    confirmText: '好的',
  })
  if (cancel) {
    return
  }
  // TODO 原项目没有页面
  useToast('跳转自提页')
}

/** 申请归还 */
export function handleShenQingGuiHuan({ oid }: BaseOptions) {
  useConsole?.log('handleShenQingGuiHuan')

  useGlobalCache().currentOrderId = oid

  useNav('/order/apply-for-return', { oid })
}

/** 定损结果 */
export function handleDingSunJieGuo({ oid }: BaseOptions) {
  useConsole?.log('handleDingSunJieGuo')

  useGlobalCache().currentOrderId = oid

  useNav('/order/loss-detail', { oid })
}

/** 违约金 */
export function handleWeiYueJin({ oid }: BaseOptions) {
  useConsole?.log('handleWeiYueJin')

  useGlobalCache().currentOrderId = oid

  useNav('/order/liquidated', { oid })
}

/** 续租 */
export async function handleXuZu({ oid }: BaseOptions) {
  const { cancel } = await useModal({
    title: '温馨提示',
    content: '确认续租',
    confirmText: '确认',
  })
  if (cancel) {
    return
  }

  useLoading(true)
  const [err, _res] = await to(orderApi.recyclerenew({ oid }))
  useHideLoading()
  if (err) {
    return
  }
  // TODO 跳转帐单详情页
  // useToast('跳转帐单详情页')
  uni.$emit('refreshOrderItem', oid)
}

/** 买断 */
export async function handleMaiDuan({ oid }: BaseOptions, paymentChannel?: payKeyItem) {
  const { cancel } = await useModal({
    title: '温馨提示',
    content: '买断需支付剩余尾款',
    confirmText: '确认',
  })
  if (cancel) {
    return
  }

  // #ifdef H5
  // TODO 原项目的一个支付弹窗
  useToast('打开支付弹窗')
  // #endif

  // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO || MP-KUAISHOU
  const payType = UNI_PLATFORM === 'mp-kuaishou' ? paymentChannel?.provider : ''
  useLoading(true)
  const [err, res] = await to(orderApi.orderBuyout(oid, { payType }))
  useHideLoading()
  if (err) {
    return
  }

  if (res === 'success') {
    return useModal({
      title: '温馨提示',
      content: '订单已买断，欢迎再次租赁',
      showCancel: false,
      confirmText: '好的',
    })
  }

  // #ifdef MP-ALIPAY
  try {
    await useAliPay({ tradeNO: res })
  }
  catch { }
  // #endif
  // #ifdef MP-KUAISHOU
  await to(useKuaishouPay({ order_no: res.order_no, order_info_token: res.order_info_token }, paymentChannel))
  // #endif
  // // TODO 可能还未完全写完
  // // pages/order/orderList/minjs/order.js:148
  // const { route } = useCurrentPage()
  // if (route === '/pages/order/detail') {
  //   uni.$emit('refreshOrderDetail', oid)
  // }
  // else {
  //   //订单列表自动刷新
  //   uni.$emit('refreshOrderItem', oid)
  // }
  uni.$emit('refreshOrderDetail', oid)
  // #endif
}

/** 取消订单 */
export async function handleQuXiaoDingDan({ oid }: BaseOptions) {
  useConsole?.log('handleQuXiaoDingDan')

  useGlobalCache().currentOrderId = oid

  useNav('/order/cancel-or-refund', {
    type: 'cancel',
    oid,
  })
}

/** 申请退款 */
export async function handleShenQingTuiKuan({ oid }: BaseOptions) {
  useConsole?.log('handleShenQingTuiKuan')

  useGlobalCache().currentOrderId = oid

  useNav('/order/cancel-or-refund', {
    type: 'refund',
    oid,
  })
}

/** 服务保障 */
export function handleFuWuBaoZhang({ oid }: BaseOptions) {
  useConsole?.log('handleFuWuBaoZhang')

  useGlobalCache().currentOrderId = oid

  useNav('/order/server', { oid })
}

/** 联系商家 */
export function handleLianXiShangJia(/* { oid }: BaseOptions */) {
  const appConfig = useAppConfig()
  uni.makePhoneCall({
    phoneNumber: appConfig.appletSet.phone.value!,
  })
}

interface FengKongBuLuOptions extends BaseOptions {
  mode: number
}
/** 风控补录 */
export function handleFengKongBuLu({ oid, mode }: FengKongBuLuOptions) {
  useGlobalCache().currentOrderId = oid

  useNav('/attachment/risk-control', { oid, mode })

  // #ifdef MP-ALIPAY || MP-WEIXIN || MP-TOUTIAO || MP-KUAISHOU
  // useNav('/webview', {
  //   src: encodeURIComponent(`${import.meta.env.VITE_H5_URL}/pages/goto?path=${encodeURIComponent(`attachment/risk-control?oid=${oid}`)}&utoken=${uni.getStorageSync('token')}&appletId=${uni.getAccountInfoSync().miniProgram.appId}`),
  // })
  // #endif
}

interface ShouHuoBuLuOptions extends BaseOptions {
  mode: number
  type: string
}
/** 收货补录 */
export function handleShouHuoBuLu({ oid, mode, type }: ShouHuoBuLuOptions) {
  useGlobalCache().currentOrderId = oid

  useNav('/attachment/receiving', { oid, mode, type })

  // #ifdef MP-ALIPAY || MP-WEIXIN || MP-TOUTIAO || MP-KUAISHOU
  // useNav('/webview', {
  //   src: encodeURIComponent(`${import.meta.env.VITE_H5_URL}/pages/goto?path=${encodeURIComponent(`attachment/receiving?oid=${oid}`)}&utoken=${uni.getStorageSync('token')}&appletId=${uni.getAccountInfoSync().miniProgram.appId}`),
  // })
  // #endif
}
